<template>
  <div class="profile-container">
    <h1>个人中心</h1>

    <div class="profile-info">
      <el-avatar :src="user.avatar" size="100" />
      <div class="user-details">
        <h2>{{ user.username }}</h2>
        <p>邮箱: {{ user.email }}</p>
        <p>电话: {{ user.phone }}</p>
        <el-button type="primary" @click="editProfile">编辑信息</el-button>
      </div>
    </div>

    <el-dialog title="编辑个人信息" v-model="editDialogVisible" width="600px" append-to-body>
      <el-form :model="user" ref="userForm" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="username">
              <el-input v-model="user.username" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="user.phone" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realNameInfo">
              <el-input v-model="user.realNameInfo" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="头像" prop="avatar">
              <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeUpload"
                @success="handleSuccess" @error="handleError">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
              <div v-if="user.avatar" class="uploaded-image">
                <img :src="user.avatar" alt="上传的头像" style="max-width: 100%; margin-top: 10px;" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer button-group">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateUser">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-tabs>
      <el-tab-pane label="待办事项">
        <h3>我的待办事项</h3>
        <el-table :data="todoList" style="width: 100%">
          <el-table-column prop="title" label="任务标题" />
          <el-table-column prop="task" label="任务内容" />
          <el-table-column prop="status" label="状态" :formatter="formatStatus" />
          <el-table-column prop="dueDate" label="截止日期" :formatter="formatDate" />
          <el-table-column label="操作"  width="200px">
            <template #default="{ row }">
              
                <el-button type="danger" @click="removeTodo(row.id)">移除</el-button>
                <el-button type="primary" @click="completeTodo(row.id)">完成</el-button>
             
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="我的任务">
        <getReceiveTask/>
      </el-tab-pane>
      <el-tab-pane label="我的发布">
        <getMyReleaseTask />
      </el-tab-pane>
      <el-tab-pane label="我的求购">
        <getBuyTransactionRecord />
      </el-tab-pane>
      <el-tab-pane label="求购商品请求">
        <getSellTransactionRecord />
      </el-tab-pane>

    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import todoEventApi from "@/api/todoEvent";
import { getEventByReceiverId } from '@/api/event';
import { getUserInfo, updateUserInfo } from '@/api/user';
import { uploadImage } from "@/api/upload";
import { getTransactionRecordByToken, rejectTransaction, acceptTransaction, getMyBuyRecordByToken } from "@/api/transactionRecord";
import getBuyTransactionRecord from "./components/MyBuyTransactionsRecord.vue"
import getSellTransactionRecord from "./components/MySellTransactionsRecord.vue"
import getReceiveTask from "./components/MyReceiveTask.vue"
import getMyReleaseTask from "./components/MyPublishTask.vue"

const user = ref({
  username: '',
  email: '',
  phone: '',
  realNameInfo: '',
  avatar: '',
});
//别人买我的
const mytransactionsRecordList = ref([]);







const getMytransactionsRecordList = async () => {
  const res = await getTransactionRecordByToken();
  if (res.code == 200) {
    mytransactionsRecordList.value = res.data;
  }

};


const rejectTransactionWay = async (id) => {
  console.log("id为", id);
  const res = await rejectTransaction(id);
  if (res.code == 200) {
    getMytransactionsRecordList();
  }
};

//接受交易
const receiveTransaction = async (id) => {
  const res = await acceptTransaction(id);
  if (res.code == 200) {
    getMytransactionsRecordList();
  }
};


const editDialogVisible = ref(false);
const todoList = ref([]);
const eventReceiveList = ref([]);

// 获取用户信息
const getUserData = () => {
  getUserInfo().then(res => {
    user.value = res.data;
  });
};

//卖家状态
const getConfirmationText = (status) => {
  switch (status) {
    case 0: return '待确认';
    case 1: return '已确认';
    case 2: return '已拒绝';
    default: return '未知状态';
  }
}

//交易状态
const getTransactionStatusText = (status) => {
  switch (status) {
    case 0: return '待确认';
    case 1: return '已完成';
    case 2: return '等待卖家确认';
    case 3: return '已取消交易';
    case 4: return '等待买家支付';
    default: return '未知状态';
  }
}


// 更新用户信息
const updateUser = () => {
  const params = {
    username: user.value.username,
    email: user.value.email,
    phone: user.value.phone,
    realNameInfo: user.value.realNameInfo,
    avatar: user.value.avatar,
  };
  updateUserInfo(params).then(() => {
    editDialogVisible.value = false;
  });
};

// 上传文件之前的钩子
const beforeUpload = (file) => {
  uploadImage(file).then(data => {
    user.value.avatar = data; // 假设服务器返回的 URL 字段是 data
  });
  return true; // 返回 true 表示可以上传
};

// 上传成功的回调
const handleSuccess = (response) => {
  user.value.avatar = response; // 更新头像 URL
};

// 上传失败的回调
const handleError = (err) => {
  console.error("上传失败:", err);
};

// 获取待办事项列表
const getTodoList = async () => {
  const res = await todoEventApi.getEventListByUserId();
  todoList.value = res.data;
};

// 获取接取的任务列表
const getEventReceiveList = () => {
  getEventByReceiverId().then(res => {
    eventReceiveList.value = res.data;
  });
};

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return ''; // 处理空值
  const date = new Date(cellValue);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
  }).replace(/\//g, '-');
};

// 格式化状态
const formatStatus = (row, column, cellValue) => {
  switch (cellValue) {
    case 0: return '未开始';
    case 1: return '进行中';
    case 2: return '已完成';
    default: return '未知状态';
  }
};

// 移除待办事项
const removeTodo = (id) => {
  todoEventApi.deleteTodoEvent(id).then(() => {
    getTodoList();
  });
};

// 编辑个人信息
const editProfile = () => {
  editDialogVisible.value = true;
};

onMounted(() => {
  getTodoList();
  getEventReceiveList();
  getUserData();
  getMytransactionsRecordList();
});
</script>

<style scoped>
.profile-container {
  width: 95vw;
  height: 100vh;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.profile-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.user-details {
  margin-left: 20px;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>